#include "log.h"
#include "wlroots.hpp"
#include "wlroots-full.hpp"
#include <glib.h>
#include <stdio.h>

static FILE *log_file = NULL;

static void wlr_log_handler(enum wlr_log_importance importance, const char *fmt, va_list args) {
    if (!log_file) {
        return;
    }

    const char *level_prefix;
    switch (importance) {
    case WLR_SILENT:
        level_prefix = "[SILENT]";
        break;
    case WLR_ERROR:
        level_prefix = "[ERROR]";
        break;
    case WLR_INFO:
        level_prefix = "[INFO]";
        break;
    case WLR_DEBUG:
        level_prefix = "[DEBUG]";
        break;
    default:
        level_prefix = "[UNKNOWN]";
        break;
    }

    fprintf(log_file, "%s ", level_prefix);
    vfprintf(log_file, fmt, args);
    fprintf(log_file, "\n");
    fflush(log_file);
}


void log_init(void)
{
    g_autofree gchar* wlr_log_dir = g_build_filename(g_get_user_data_dir(), "bwl", "log", NULL);
    if (!g_file_test(wlr_log_dir, G_FILE_TEST_IS_DIR)) {
        if (g_mkdir_with_parents(wlr_log_dir, 0755)) {
            g_error("mkdir %s error: %s", wlr_log_dir, strerror(errno));
            exit(1);
        }
    }

    g_autofree gchar* wlr_log_path = g_build_filename(wlr_log_dir, "bwl.log", NULL);
    log_file = fopen(wlr_log_path, "w");
    if (!log_file) {
        g_error("Failed to open log file\n");
        exit(1);
    }
    wlr_log_init(WLR_DEBUG, wlr_log_handler);
}
